<?php
/**
 * Клас базовой модели c_base_model
 *
 * @author tonatos
 */
class c_web_users_model extends c_base_model {

    public $id;
    public $username;
    public $activated;
    public $cachepwd;
    public $password;
    public $blocked;

    public function load(){
        global $modx;
        $data = $modx->db->get_records("select * from ".$modx->getFullTableName("web_users")." u, ".$modx->getFullTableName("web_user_attributes")." a WHERE a.internalKey = u.id and u.id=".(int)$this->id);

        if (empty($data)){
            throw new Exception('Объект не найден '. $this->m_table." id = $this->id");
            return false;
        }

        $data = $data[0];
        unset($data->id);
        unset($data->internalKey);

        $addon = $modx->db->get_records("select * from ".$modx->getFullTableName("web_user_settings")." where webuser=".(int)$this->id);
        if ($addon){
            foreach ($addon as $row){                
                $key =$row->setting_name;
                $this->$key=$row->setting_value;
            }
        }
        
        foreach ($data as $key=>$value){
            $this->$key = $value;
        }

        return true;
    }

    public function  prepare_data() {
        global $modx;
        $data = parent::prepare_data();

        //Разбираем данные на массивы
        $web_user = array();
        $web_user_attributes = array();
        $web_user_settings = array();

        //базовые
        $rows = array('id','username','password','cachepwd');
        foreach ($rows as $row){
            if (isset($data[$row])){
                $web_user[$row] = $data[$row];
                unset($data[$row]);
            }
        }

        //атрибуты
        $sql = "show columns from ".$modx->getFullTableName('web_user_attributes');
        $rows = $modx->db->get_records($sql);

        foreach ($rows as $row){
            if (($row->Field=="id")||($row->Field=='internalKey')) continue;
            if (isset($data[$row->Field])){
                $web_user_attributes[$row->Field] = $data[$row->Field];
                unset($data[$row->Field]);
            }
        }

        //все остальное
        foreach ($data as $key => $value) {
            $web_user_settings[$key]= $value;
        }

        $this->m_web_user = $web_user;
        $this->m_web_user_attributes = $web_user_attributes;
        $this->m_web_user_settings = $web_user_settings;

        return $web_user;
    }

    public function  after_insert() {
        global $modx;
        $this->m_web_user_attributes['internalKey'] = $this->id;
        
        //Сохраняем атрибуты
        $keys = array_keys($this->m_web_user_attributes);
        $values = array_values($this->m_web_user_attributes);

        $sql="insert into ".$modx->getFullTableName("web_user_attributes")." (".implode(",",$keys).") values (".implode(",",$values).")";
        $modx->db->query($sql);

        //Сохраняем значения
        if (!empty($this->m_web_user_settings)){
            $wus = $modx->getFullTableName("web_user_settings");
            foreach ($this->m_web_user_settings as $key=>$value) {
                $key = $modx->db->escape($key);
                $sql = "insert into $wus (webuser,setting_name,setting_value) values ($this->id,'$key',$value)";
                $modx->db->query($sql);

            }
        }

    }

    public function  after_update() {
        global $modx;
        //Сохраняем атрибуты
        if (!empty($this->m_web_user_attributes)){
            $sql=array();
            foreach($this->m_web_user_attributes as $key=>$value){
                $sql[] = "$key = $value ";
            }
            $sql="update ".$modx->getFullTableName("web_user_attributes")." set ".implode(",",$sql)." where internalKey = $this->id";
            $modx->db->query($sql);
        }

        if (!empty($this->m_web_user_settings)){
            $wus = $modx->getFullTableName("web_user_settings");
            foreach ($this->m_web_user_settings as $key=>$value) {
                $key = $modx->db->escape($key);

                $row = $modx->db->get_record("web_user_settings","webuser=$this->id and setting_name = '$key'");

                if (!empty($row)){
                    //update
                    $sql = "update $wus set setting_value=$value where webuser=$row->webuser";
                    $modx->db->query($sql);
                }else{
                    //insert
                    $sql = "insert into $wus (webuser,setting_name,setting_value) values ($this->id,'$key',$value)";
                    $modx->db->query($sql);

                }
            }
        }

        
    }

    public function find_by_email($email){
        global $modx;
        $email = $modx->db->escape(trim($email));

        $attributes = $modx->db->get_record("web_user_attributes","lower(email) = lower('$email')");
        if ($attributes===false) return false;

        $this->id = $attributes->internalKey;

        return true;
    }

    public function find($username){
        global $modx;
        $username = $modx->db->escape(trim($username));        

        $row = $modx->db->get_record("web_users","lower(username) = lower('$username')");
        if ($row===false) return false;

        $this->id = $row->id;
        return true;
    }

    public function get_photo($prefix=""){
        if (empty($this->photo)) {
            return "assets/snippets/mvc/data/workplace/avatar_100x100.jpg";
        }

        $thumb = $this->photo;
        if (!empty($prefix)){
            $thumb = str_replace("webusers/$this->id/","webusers/$this->id/{$prefix}_",$thumb);
        }

        return $thumb;
    }
}
?>
